package raft

import (
	"edata-hub/pkg/raft/services"
	"golang.org/x/net/context"
	"time"
)

// @Description:重置选举时间
// @receiver r
func (r *Raft) ResetElectionTime() {
	t := time.Now()
	timeout := time.Duration(15) * time.Second
	r.ElectionTime = t.Add(timeout) //下一次超时时间定在150-300ms之后
}

// @Description: 请求投票
// @receiver r
func (r *Raft) RequestVote() {
	r.Term++ //进入下一个任期
	req := new(services.VoteReq)
	req.Address = r.Addr
	req.Term = r.Term
	req.LastLogIndex = r.Log.lastLog().Index
	req.LastLogTerm = r.Log.lastLog().Term
	for peer, _ := range r.Peers {
		client, _ := r.CreateGRPCClient(peer)
		resp, err := client.OnHandleVoteReq(context.Background(), req)
		if err != nil {
			r.Msg.Error("%s request vote fail", err)
			//TODO 无法通信，可能需要将该节点从peers中删除
			return
		} else {
			r.VoteChan <- resp
		}
	}
}
